/*
	我的机构人员
 */
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.Customized;
using SOEI.Solution.Customized.Dtos;
using SOEI.Solution.DomainEntities.Parameters.DomainService;
using SOEI.Solution.DomainEntities.Parameters.Dtos;
using SOEI.Solution.Helper;
using SOEI.Solution.Integratedes.ElectronicSignet;
using SOEI.Solution.Integratedes.ElectronicSignet.DomainService;
using SOEI.Solution.Integratedes.ElectronicSignet.Dtos;
using SOEI.Solution.Integratedes.Organization.DomainService;
using SOEI.Solution.Integratedes.Organization.Dtos;
using SOEI.Solution.StructEntities.Organization;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;


namespace SOEI.Solution.Integratedes.Organization
{
	/// <summary>
	/// 【扩展模块】  <br/>
	/// 【功能描述】  ：我的机构人员 模块<br/>
	/// 【创建日期】  ：2020.05.21 <br/>
	/// 【开发人员】  ：static残影<br/>
	///</summary>
	[AbpAuthorize()]
	[ApiExplorerSettings(GroupName = "Manager", IgnoreApi = false)]
	public class OursEconomyPersonAppService : SolutionAppServiceBase, IOursEconomyPersonAppService
	{
		/// <summary>
		///【OEconomyPerson】仓储层
		/// </summary>
		private readonly IRepository<OEconomyPerson, string> _oeconomypersonRepository;

		/// <summary>
		///【机构人员】机构人员领域
		/// </summary>
		private readonly IOEconomyPersonManager _oeconomypersonManager;

		/// <summary>
		///【机构人员】机构人员变更领域
		/// </summary>
		private readonly IOEconomyPersonChangeManager _oeconomyPersonChangeManager;

		/// <summary>
		///【机构信息】领域服务
		/// </summary>
		private readonly IOEconomyOrganiManager _oeconomyorganiManager;

		/// <summary>
		/// 【Parameter】参数的领域服务
		/// </summary>
		private readonly IParameterManager _parameterManager;

		/// <summary>
		/// 【印章授权】电子印章授权领域服务
		/// </summary>
		private readonly ISignetGrantManager _signetGrantManager;

		/// <summary>
		/// 【承若书】电子印章授权领域服务
		/// </summary>
		private readonly IPledgeBookManager _pledgeBookManager;

		public OursEconomyPersonAppService(
			IRepository<OEconomyPerson, string> oeconomypersonRepository,
			IOEconomyPersonManager oeconomypersonManager,
			IOEconomyOrganiManager oeconomyorganiManager,
			IOEconomyPersonChangeManager oeconomyPersonChangeManager,
			IParameterManager parameterManager,
			ISignetGrantManager signetGrantManager,
			IPledgeBookManager pledgeBookManager
		)
		{
			_oeconomypersonRepository = oeconomypersonRepository;
			_oeconomypersonManager = oeconomypersonManager;
			_oeconomyorganiManager = oeconomyorganiManager;
			_oeconomyPersonChangeManager = oeconomyPersonChangeManager;
			_parameterManager = parameterManager;
			_signetGrantManager = signetGrantManager;
			_pledgeBookManager = pledgeBookManager;
		}

		#region -------------------------------------------------辅助工具生成---------------------------------------------- 

		/// <summary>
		///【OEconomyPerson】获取的分页列表信息
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task<PagedResultDto<OEconomyPersonListDto>> GetPaged(GetOEconomyPersonsInput input)
		{

			var userEntity = await this.GetPersonChecker();

			// 只获取自己机构的
			var query = this._oeconomypersonManager.QueryUnionEntityForBledgeBookListAsNoTracking()
						  //模糊搜索 字段RYMC
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.RYMC.Contains(input.FilterText) || a.LXDH.Contains(input.FilterText))
						  .WhereIf(!input.SFZH.IsNullOrWhiteSpace(), a => a.SFZH == input.SFZH)
						  .WhereIf(!input.ZGZH.IsNullOrWhiteSpace(), a => a.ZGZH == input.ZGZH)
						  .Where(x => x.JGBH == userEntity.OriginalNumber) // 只获取自己机构的
			;
			// TODO:根据传入的参数添加过滤条件

			var count = await query.CountAsync();

			var entityList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			var entityListDtos = ObjectMapper.Map<List<OEconomyPersonListDto>>(entityList);

			return new PagedResultDto<OEconomyPersonListDto>(count, entityListDtos);
		}

		/// <summary>
		///【OEconomyPerson】通过指定id获取MemberListDto信息
		/// </summary>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task<OEconomyPersonListDto> GetById(EntityDto<string> input)
		{
			var userEntity = await this.GetPersonChecker();

			var entity = await _oeconomypersonRepository.GetAsync(input.Id);

			var dto = ObjectMapper.Map<OEconomyPersonListDto>(entity);
			return dto;
		}

		/// <summary>
		///【Company】 获取编辑
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task<GetOEconomyPersonForEditOutput> GetForEdit(EntityDto<string> input)
		{
			var userEntity = await this.GetPersonChecker();

			var output = new GetOEconomyPersonForEditOutput();
			// 编辑时候选择的下拉框人员类型
			var queryPersonType = this._parameterManager.QueryPersonType();
			var personTypeList = await queryPersonType
										.AsNoTracking()
										.ToListAsync();
			personTypeList = personTypeList.Where(x => !x.Id.Contains("0")).ToList(); // 过滤掉管理员类型
			output.PersonTypes = ObjectMapper.Map<ICollection<ParameterListDto>>(personTypeList);

			OEconomyPersonEditDto editDto;

			if (!string.IsNullOrEmpty(input.Id))
			{
				var entity = await _oeconomypersonRepository.GetAsync(input.Id);
				editDto = ObjectMapper.Map<OEconomyPersonEditDto>(entity);
			}
			else
			{
				editDto = new OEconomyPersonEditDto();
				editDto.JGBH = userEntity.OriginalNumber; // 默认填写机构编号
			}
			output.EconomyPerson = editDto;
			return output;
		}

		/// <summary>
		///【OEconomyPerson】 添加或者修改的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task CreateOrUpdate(CreateOrUpdateOEconomyPersonInput input)
		{


			if (!string.IsNullOrEmpty(input.OEconomyPerson.Id))
			{
				await Update(input.OEconomyPerson);
			}
			else
			{
				await Create(input.OEconomyPerson);
			}
		}
		/// <summary>
		///【OEconomyPerson】新增
		/// </summary>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		protected virtual async Task<OEconomyPersonEditDto> Create(OEconomyPersonEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增
			var userEntity = await this.GetPersonChecker();

			var entity = ObjectMapper.Map<OEconomyPerson>(input);
			// 获取新的序列号
			entity.Id = _oeconomypersonManager.GetNewSequenceCode();
			// 设置默认状态
			entity.RYZT = ((int)EApprovalStatus.WaitSubmit).ToString();
			// 默认属于机构编号
			entity.JGBH = userEntity.OriginalNumber;
			// 录入时间
			entity.LRSJ = Abp.Timing.Clock.Now.ToString("yyyyMMddHHmmss");

			//调用领域服务
			entity = await _oeconomypersonManager.CreateAsync(entity);

			var dto = ObjectMapper.Map<OEconomyPersonEditDto>(entity);
			return dto;
		}

		/// <summary>
		///【OEconomyPerson】编辑
		/// </summary>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		protected virtual async Task Update(OEconomyPersonEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新
			var key = input.Id;
			var entity = await _oeconomypersonRepository.GetAsync(key);
			// 设置默认状态
			input.RYZT = ((int)EApprovalStatus.WaitSubmit).ToString();
			//input.LRSJ = Abp.Timing.Clock.Now.ToString("yyyyMMddHHmmss");
			//  input.MapTo(entity);
			//将input属性的值赋值到entity中
			ObjectMapper.Map(input, entity);
			await _oeconomypersonManager.UpdateAsync(entity);
		}

		/// <summary>
		///【OEconomyPerson】删除信息
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task Delete(EntityDto<string> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _oeconomypersonManager.DeleteAsync(input.Id);
		}

		/// <summary>
		///【OEconomyPerson】 批量删除Member的方法
		/// </summary>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task BatchDelete(List<string> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _oeconomypersonManager.BatchDelete(input);
		}

		#endregion

		#region -------------------------------------------------用户自定义------------------------------------------------

		/// <summary>
		/// 获取初始化备案中的人员清单（原始变更表清单）【初始化备案】
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task<PagedResultDto<OEconomyPersonChangeListDto>> GetInitPaged(GetOEconomyPersonChangesInput input)
		{

			var userEntity = await this.GetPersonChecker();

			// 只获取自己机构的
			var query = this._oeconomyPersonChangeManager.QueryUnionEntityListAsNoTracking()
						  //模糊搜索 字段RYMC
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.RYMC.Contains(input.FilterText) || a.LXDH.Contains(input.FilterText))
						  .WhereIf(!input.SFZH.IsNullOrWhiteSpace(), a => a.SFZH == input.SFZH)
						  .WhereIf(!input.ZGZH.IsNullOrWhiteSpace(), a => a.ZGZH == input.ZGZH)
						  .Where(x => x.JGBH == userEntity.OriginalNumber) // 只获取自己机构的
			;
			// TODO:根据传入的参数添加过滤条件

			var count = await query.CountAsync();

			var entityList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			var entityListDtos = ObjectMapper.Map<List<OEconomyPersonChangeListDto>>(entityList);

			return new PagedResultDto<OEconomyPersonChangeListDto>(count, entityListDtos);
		}

		/// <summary>
		/// 获取待选择的经济机构人员 【机构人员】
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task<PagedResultDto<OEconomyPersonListDto>> GetSelectPaged(GetOEconomyPersonsInput input)
		{

			var userEntity = await this.GetPersonChecker();

			// 只获取自己机构的
			var query = this._oeconomypersonManager.QueryUnionEntityListAsNoTracking()
						  //模糊搜索 字段RYMC
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.RYMC.Contains(input.FilterText) || a.LXDH.Contains(input.FilterText))
						  .WhereIf(!input.SFZH.IsNullOrWhiteSpace(), a => a.SFZH == input.SFZH)
						  .WhereIf(!input.ZGZH.IsNullOrWhiteSpace(), a => a.ZGZH == input.ZGZH)
						  .Where(x => x.JGBH.Trim() == string.Empty) // 获取可选择的列表
			;
			// TODO:根据传入的参数添加过滤条件

			var count = await query.CountAsync();

			var entityList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			var entityListDtos = ObjectMapper.Map<List<OEconomyPersonListDto>>(entityList);

			return new PagedResultDto<OEconomyPersonListDto>(count, entityListDtos);
		}

		/// <summary>
		/// 初始化备案中的人员信息编辑(获取人员变更表编辑数据) 【人员变更】
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task<GetOEconomyPersonChangeForEditOutput> GetPersonChangeForEdit(EntityDto<string> input)
		{
			var userEntity = await this.GetPersonChecker();

			var output = new GetOEconomyPersonChangeForEditOutput();
			// 编辑时候选择的下拉框人员类型
			var queryPersonType = this._parameterManager.QueryPersonType();
			var personTypeList = await queryPersonType
										.AsNoTracking()
										.ToListAsync();

			personTypeList = personTypeList.Where(x => !x.Id.Contains("0")).ToList(); // 过滤掉管理员类型
			output.PersonTypes = ObjectMapper.Map<ICollection<ParameterListDto>>(personTypeList);

			OEconomyPersonChangeEditDto editDto;

			if (!string.IsNullOrEmpty(input.Id))
			{
				var entity = await this._oeconomyPersonChangeManager.FindByIdAsync(input.Id);
				editDto = ObjectMapper.Map<OEconomyPersonChangeEditDto>(entity);
			}
			else
			{
				editDto = new OEconomyPersonChangeEditDto();
				editDto.JGBH = userEntity.OriginalNumber; // 默认填写机构编号
			}
			output.EconomyPerson = editDto;
			return output;
		}

		/// <summary>
		///申请指定工作人员纳入我的机构 【初始化备案】
		/// </summary>
		/// <param name="input">人员编号</param>
		/// <returns></returns>
		public async Task AcceptPerson(EntityDto<string> input)
		{
			var userEntity = await this.GetPersonChecker();

			if (string.IsNullOrEmpty(input.Id))
			{
				throw new UserFriendlyException("人员编号不能为空！");
			}
			if (await this._oeconomypersonManager.IsExistPersonChange(userEntity.OriginalNumber, input.Id))
			{
				throw new UserFriendlyException("人员已经在我们的机构，并且正在进行变更处理！");
			}
			// 需要判断这个人能不能用
			await this._oeconomypersonManager.AcceptPerson(userEntity.OriginalNumber, input.Id);
		}

		

		/// <summary>
		/// 获取测试方法
		/// </summary>
		/// <returns></returns>
		public async Task GetTestFunction(string OriginalNumber)
		{

			var userEntity = await this.GetPersonChecker();
			// 1. 获取机构
			var originalEntity = await this._oeconomyorganiManager.FindByIdAsync(OriginalNumber);

			// 如果不存在生成一个管理员
			if (await _oeconomypersonManager.IsExistAdminAccount(originalEntity.Id))
			{
				// 创建一个管理员
				var adminEntity = EntityHelper.GetNewOEconomyAdmin(originalEntity, "111111");

				await this._oeconomypersonManager.GenerateAdminAccount(adminEntity);
			}
		}
		#endregion

		#region -------------------------------------------------新模式许可------------------------------------------------

		/// <summary>
		/// 获取正式人员清单和承诺书清单【新模式许可】
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task<PagedResultDto<OEconomyPersonListDto>> GetNewLicenseInitPaged(GetOEconomyPersonsInput input)
		{

			var userEntity = await this.GetPersonChecker();

			// 只获取自己机构的
			var query = this._oeconomypersonManager.QueryUnionEntityForBledgeBookListAsNoTracking()
						 //模糊搜索 字段RYMC
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.RYMC.Contains(input.FilterText) || a.LXDH.Contains(input.FilterText))
						  .Where(x => x.JGBH == userEntity.OriginalNumber) // 只获取自己机构的
			;
			// TODO:根据传入的参数添加过滤条件

			var count = await query.CountAsync();

			var entityList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			var entityListDtos = ObjectMapper.Map<List<OEconomyPersonListDto>>(entityList);

			return new PagedResultDto<OEconomyPersonListDto>(count, entityListDtos);
		}

		/// <summary>
		/// 批量新模式许可申请（初始化中使用）【新模式许可】
		/// </summary>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task LicenseBatchApply(LicenseAppliesInput input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			var userEntity = await this.GetPersonChecker();
			if (!input.PledgeBookID.HasValue) {
				throw new UserFriendlyException("承若书编号不存在！");
			}
			var pledaeBookEntity = await this._pledgeBookManager.FindByIdAsync(input.PledgeBookID.Value);
			// 找到选中的所有人员
			var personEntityList = await this._oeconomypersonManager.Query().Where(x => input.Ids.Contains(x.Id)).ToListAsync();

			foreach (var personEntity in personEntityList) {

				personEntity.PledgeBookID = pledaeBookEntity.Id;
			}
		}

		/// <summary>
		/// 注销新模式许可【新模式许可】
		/// </summary>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task LicenseCancel(EntityDto<string> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			var userEntity = await this.GetPersonChecker();
			var entity = await _oeconomypersonRepository.GetAsync(input.Id);
			entity.PledgeBookID = null; // 注销就是清空这个字段
		}

		/// <summary>
		/// 为新模式许可批量申请做数据准备（目前返回一个新的承若书实体）【新模式许可】
		/// </summary>
		public async Task<PledgeBookEditDto> GetForBatchApplyEdit()
		{
			var userEntity = await this.GetPersonChecker();
			// 创建一个新的承诺书
			var entity = EntityHelper.GetNewPledgeBook();
			entity.JGBH = userEntity.OriginalNumber;
			var output = ObjectMapper.Map<PledgeBookEditDto>(entity);
			return output;
		}

		/// <summary>
		/// 批量新模式许可申请（人员资质中使用）【新模式许可】
		/// </summary>
		//[AbpAuthorize(OEconomyPersonPermissions.Node)]
		public async Task PersonLicenseBatchApply(PersonLicenseAppliesInput input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			var userEntity = await this.GetPersonChecker();

			var pledaeBookEntity = ObjectMapper.Map<PledgeBook>(input.PledgeBook);

			// 创建 
			await this._pledgeBookManager.CreateAsync(pledaeBookEntity);

			// 找到选中的所有人员
			var personEntityList = await this._oeconomypersonManager.Query().Where(x => input.Ids.Contains(x.Id)).ToListAsync();

			foreach (var personEntity in personEntityList)
			{

				personEntity.PledgeBookID = pledaeBookEntity.Id;
			}
		}

		/// <summary>
		/// 获取卡片信息
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<dynamic> GetForView(EntityDto<string> input) 
		{
			
			var userEntity = await this.GetPersonChecker();
			// 1. 获取人员信息
			var entity = await _oeconomypersonRepository.GetAsync(input.Id);
			// 2. 需要人员照片
			var pledgeEntity = await this._pledgeBookManager.FindByIdAsync(entity.PledgeBookID.Value);
			// 3. 需要人员照片

			// 4.生成二维码
			var uri = "http://www.baidu.com"; // 默认打开这个
			var bitmap = QRCoderHelper.GetPTQRCode(uri, 5);
			var result = Base64Convert.BitmapToBase64(bitmap);

			return new
			{
				QRImage = result, // 二维码
				RYMC    = entity.RYMC,
				WYBM    = "12UZPDW-CCEFPOIJNIIANNA-OOPR",
				Date    = "2021年12月12日"
			};
		}
		#endregion

	}
}
